import tkinter as tk
from tkinter import filedialog, messagebox
import pandas as pd
from tqdm import tqdm
import tkinter.ttk as ttk
import time

def match_files():
    # 获取文件路径
    source_file_path = source_file_entry.get()
    match_file_path = match_file_entry.get()

    if not source_file_path or not match_file_path:
        messagebox.showerror("错误", "请选择文件路径！")
        return

    try:
        # 读取 Excel 文件
        source_df = pd.read_excel(source_file_path, dtype=str)
        match_df = pd.read_excel(match_file_path, dtype=str)
    except Exception as e:
        messagebox.showerror("错误", f"读取文件时出错：{e}")
        return

    # 预留10列空白列
    for i in range(10):
        col_name = f"Matched ID {i+1}"
        source_df[col_name] = ""

    # 匹配数据
    progress_bar['maximum'] = len(source_df)
    for index_source, row_source in tqdm(source_df.iterrows(), total=len(source_df), desc="匹配进度"):
        matched_ids = []
        for _, row_match in match_df.iterrows():
            if row_source["A"] == row_match["F"] and row_source["B"] == row_match["G"]:
                matched_ids.append(row_match["B"])
                

        # 将匹配的编号逐列添加到 source_df 的相应行中
        for i, matched_id in enumerate(matched_ids):
            if i < 10:
                col_name = f"Matched ID {i+1}"
                source_df.at[index_source, col_name] = matched_id
                

        # 更新进度条
        progress_bar['value'] = index_source + 1
        root.update_idletasks()

    # 写入匹配结果到新的 Excel 文件
    try:
        save_path = "C:/matched_result.xlsx"
        source_df.to_excel(save_path, index=False)
        messagebox.showinfo("成功", f"匹配完成，结果保存为 {save_path}")
    except Exception as e:
        messagebox.showerror("错误", f"保存文件时出错：{e}")

    
# 创建 GUI
root = tk.Tk()
root.title("Excel 数据匹配")

# 标签和文本框用于显示文件路径
source_file_label = tk.Label(root, text="被匹配文件路径：")
source_file_label.grid(row=0, column=0, padx=5, pady=5)
source_file_entry = tk.Entry(root, width=50)
source_file_entry.grid(row=0, column=1, padx=5, pady=5)

match_file_label = tk.Label(root, text="匹配文件路径：")
match_file_label.grid(row=1, column=0, padx=5, pady=5)
match_file_entry = tk.Entry(root, width=50)
match_file_entry.grid(row=1, column=1, padx=5, pady=5)

# 选择文件按钮
source_file_button = tk.Button(root, text="选择文件", command=lambda: source_file_entry.insert(tk.END, filedialog.askopenfilename()))
source_file_button.grid(row=0, column=2, padx=5, pady=5)

match_file_button = tk.Button(root, text="选择文件", command=lambda: match_file_entry.insert(tk.END, filedialog.askopenfilename()))
match_file_button.grid(row=1, column=2, padx=5, pady=5)

# 匹配按钮
match_button = tk.Button(root, text="匹配", command=match_files)
match_button.grid(row=2, column=1, padx=5, pady=5)

# 进度条
progress_bar = ttk.Progressbar(root, orient="horizontal", length=300, mode="determinate")
progress_bar.grid(row=3, columnspan=3, padx=5, pady=5)

root.mainloop()